package com.errol.msgcenterclient.autoconfig;

import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.type.AnnotationMetadata;

import java.util.HashMap;
import java.util.Map;

/**
 * 根据 {@link EnableMsgCenterClient} 的配置，判断是否要自动处理配置项
 * 配置项有三个：
 * - msgcenter.mq.switcher.enableCommonProducer=true 表示启用mq顺序消息生产端
 * - msgcenter.mq.switcher.enableDingRobotProducer=true 表示启用mq批量消息生产端
 * - msgcenter.mq.switcher.enableMsgCenterService=true 表示启用 {@link com.renjia.msgcenter.service.MsgCenterService}
 * 启用任意生产端，都必须启用 MsgCenterService，否则业务端无法自动装配
 *
 * @author zhang xiao bin
 * @version v1.0
 * @date 2021/08/31
 * @since v1.1.0
 **/
public class AliYunMqProducerSelector implements ImportSelector, EnvironmentAware {

    public static final String PROPERTY_PREFIX = "msgcenter.mq.switcher.";
    public static final String ENABLE_COMMON_PRODUCER = "enableCommonProducer";
    public static final String ENABLE_DING_ROBOT_PRODUCER = "enableDingRobotProducer";
    public static final String ENABLE_MSG_CENTER_SERVICE = "enableMsgCenterService";
    public static final String ENABLE_STRING = "true";
    private ConfigurableEnvironment environment;

    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        AnnotationAttributes attributes = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(EnableMsgCenterClient.class.getName(), true));
        if (attributes != null) {
            Map<String, Object> properties = new HashMap<>(4);
            if (attributes.getBoolean(ENABLE_COMMON_PRODUCER) && !environment.containsProperty(PROPERTY_PREFIX + ENABLE_COMMON_PRODUCER)) {
                // 通过 enable 注解启用顺序消息生产端
                properties.put(PROPERTY_PREFIX + ENABLE_COMMON_PRODUCER, ENABLE_STRING);
            }
            if (attributes.getBoolean(ENABLE_DING_ROBOT_PRODUCER) && !environment.containsProperty(PROPERTY_PREFIX + ENABLE_DING_ROBOT_PRODUCER)) {
                // 通过 enable 注解启用钉钉消息生产端
                properties.put(PROPERTY_PREFIX + ENABLE_DING_ROBOT_PRODUCER, ENABLE_STRING);
            }
            if (!properties.isEmpty()) {
                // 启用 msgCenterService
                properties.put(PROPERTY_PREFIX + ENABLE_MSG_CENTER_SERVICE, ENABLE_STRING);
                environment.getPropertySources().addLast(new MapPropertySource("msgCenterClientPropertySource", properties));
            }
        }
        return new String[0];
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = (ConfigurableEnvironment) environment;
    }
}
